package com.dpiinc.TechPage.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.map
import androidx.lifecycle.Transformations.switchMap

import com.dpiinc.TechPage.api.EditNoteApi
import com.dpiinc.TechPage.api.NoteListApi
import com.dpiinc.TechPage.repository.EditNoteRepository
import com.dpiinc.TechPage.repository.NoteListRepository
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import kotlinx.coroutines.CommonPool
import kotlinx.coroutines.launch

/**
 * 笔迹列表ViewModel
 * Created by X on 2018/7/1.
 */
class NoteListViewModel(application: Application) : AndroidViewModel(application) {

    private val db = RoomAiWriterDatabase.getInstance(application);
    private val repository = NoteListRepository(RoomAiWriterDatabase.getInstance(application), NoteListApi.create())

    private val editepository = EditNoteRepository(RoomAiWriterDatabase.getInstance(application), EditNoteApi.create())
    private val loadTrigger = MutableLiveData<Unit>()
    private val loadResult = map(loadTrigger) {
        repository.loadData()
    }
    val notes = switchMap(loadResult) { it.pagedList }!!
    val networkState = switchMap(loadResult) { it.networkState }!!

    fun loadNotes() {
        loadTrigger.value = null
    }

    fun retry() {
        val listing = loadResult?.value
        listing?.retry?.invoke()
    }

    fun saveAll(){
        launch(CommonPool) { // 创建一个协程并维持一个指向它任务的引用
            val list = db.noteDao().getNotes();
            list.forEach {
                editepository.saveLocalNote(it)//TODO 刷新adapter
            }
        }
    }

}
